import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

import { getUserInfo } from '../api/user'
import { getCateList } from '../api/home'
import {getUploadToken,uploadQiniu} from '@/api/api'
import { Toast } from 'vant'
export default new Vuex.Store({
  state: {
    // 放数据的
   uid:'',
   token:"",
   userInfo:{},
    isLogin:false,
    cate:[]
  },
  //改数据
  mutations: {
    changea(state,val){
      state.a = val
    },
    change(state,{key,value}){
      state[key] = value
    },
    clear(state){
      state.uid = '',
      state.token = "",
      state.userInfo = {},
      state.isLogin = false
    }
   
  },
  //
  actions: {
    getUserInfo({commit},token){
      // console.log(json)
      //在这里直接写异步
      getUserInfo({
        token
      }).then(res=>{
        console.log(res)
        //再次存起来

        if(res.code == 0){
          commit('change',{key:'userInfo',value:res.userInfo})
          commit('change',{key:'uid',value:res.uid})
          commit('change',{key:'token',value:token})
          commit('change',{key:'isLogin',value:true})
        }else{
          Toast(res.msg)
        }
      })

     
    },
    getCate({state,commit}){
      getCateList().then(res=>{
        commit('change',{key:'cate',value:res.data})
      })
    },

     //上传
     async upload(o,fileList){

      let imageSrc  = [];

      if(!fileList || !Array.isArray(fileList) || fileList.length ===0){
        //没上传图片
        return imageSrc
      }
     //多个异步任务都执行完成  返回她们完成后的结果
      let task = fileList.map(v=>{
        return new Promise(async (resolve,reject)=>{
          let {file} = v
          let {type} = file;
          //拿到类型
          type = type.split('/')[1];
          //重新命名 随机名字
          let file_name = `${new Date().getTime()}_${Math.random()
            .toString(36)
            .slice(2)}.${type}`;
        //去服务器申请一个上传token
         let { token } = await getUploadToken();

         console.log(token)

        const formdata = new FormData();
          formdata.append("file", file);
          formdata.append("token", token);
          formdata.append("key", file_name);

          uploadQiniu(formdata).then((res) => {
            console.log(res);
            resolve(`http://toutiao.longxiaokj.com/` + res.key);
          });
        })
      })
       imageSrc = await Promise.all(task);

      return imageSrc;
    },
  },
  modules: {
  }
})
